//
//  DownLoadObserverProgressViewController.m
//  NSURLSessionStudyDemo
//
//  Created by zzp on 2018/5/6.
//  Copyright © 2018年 内蒙小猿. All rights reserved.
//

#import "DownLoadObserverProgressViewController.h"

@interface DownLoadObserverProgressViewController ()<NSURLSessionDownloadDelegate>

@property (weak, nonatomic) IBOutlet UIProgressView *LargeFileProgress;
@property (nonatomic,strong)NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
@property (nonatomic, strong) NSData *data;

@end

@implementation DownLoadObserverProgressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

// 开始
- (IBAction)beginLoadButtonClick:(id)sender {
    
    //1.创建session
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    
    //2.创建task
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_03.mp4"];
    
    /*
     location:文件的临时保存路径
     注意:它内部已经完成了边下载边写入数据的操作
     */
    self.downloadTask = [self.session downloadTaskWithURL:url];
    
    //3.启动
    [self.downloadTask resume];
    
}

// 暂停
- (IBAction)suspendButtonClick:(id)sender {
    
  // - (void) suspend; 暂停 ，可以恢复
    
  // - (void) cancel; 取消，不可以恢复
    
  // - (void) cancelByProducingResumeData:^(NSData * _Nullable resumeData) : ; 取消的
    
   // - (void) resume; 在创建新的任务下resume，相当于重新启动任务
    
    
    //这个方法可以拿到恢复下载需要的数据
    [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        self.data = resumeData;
    }];
    
}

// 继续下载
- (IBAction)continueButtonClick:(id)sender {
    
    //: 因为暂停下载 如果使用的是 cancel、cancelByProducingResumeData这两个方法
    //: 恢复下载就需要使用 downloadTaskWithResumeData 来重启任务
    //: 如果是通过 suspend 暂停的， 就不需要 downloadTaskWithResumeData ，直接用 resume 就可继续任务
    
    
    self.downloadTask = [self.session downloadTaskWithResumeData:self.data];
    [self.downloadTask resume];
    
}




#pragma mark NSURLSessionDownloadDelegate
/*
 1.当接收到数据的时候,写数据,该方法会调用多次
 bytesWritten:本次写入数据的大小
 totalBytesWritten:已经下载完成的数据大小
 totalBytesExpectedToWrite:文件大小
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"-didWriteData-");
    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
        self.LargeFileProgress.progress = 1.0 *totalBytesWritten/totalBytesExpectedToWrite;
    }];
}


/*
 2.恢复下载的时候调用
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    NSLog(@"didResumeAtOffset - 恢复下载");
}

/*
 3.下载完成之后调用
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"didFinishDownloadingToURL--%@--%@",location,[NSThread currentThread]);
    
    //确定文件要存放到哪里
    //caches
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *fullPath = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    //剪切文件到目的地
    NSFileManager *manager = [NSFileManager defaultManager];
    
    [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
    
        NSLog(@"%@",fullPath);
}

/*
 4.请求完成之后调用
 */
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"didCompleteWithError---%@",error);
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
